import re
from string import Template

from docx import Document
from docx.opc.package import OpcPackage
from docx.table import _Cell


class WordReplace:
    def __init__(self, filename):
        self.filename = filename
        self.word = Document(filename)  # type: OpcPackage
        self.dict = {}

    def _get_text(self):
        for paragraph in self.word.paragraphs:
            text = paragraph.text  # type: str
            _re = re.findall('\${(.*?)}', text, re.S)
            if len(_re) > 0:
                for line in _re:
                    self.dict[line] = ''

    def _get_table_text(self):
        tables = self.word.tables
        for table in tables:
            for row in table.rows:
                for cell in row.cells:  # type: _Cell
                    text = cell.text
                    _re = re.findall('\${(.*?)}', text, re.S)
                    if len(_re) > 0:
                        for line in _re:
                            self.dict[line] = ''

    def get_dict(self) -> dict:
        self._get_text()
        self._get_table_text()
        return self.dict

    def set_dict(self, _dict: dict):
        self.dict = _dict

    def set_text(self):
        for paragraph in self.word.paragraphs:
            t = Template(paragraph.text).substitute(self.dict)
            paragraph.text = t
        for table in self.word.tables:
            for row in table.rows:
                for cell in row.cells:  # type: _Cell
                    t = Template(cell.text).substitute(self.dict)
                    cell.text = t

    def replace_save(self, path):
        self.set_text()
        self.word.save(path)


if __name__ == '__main__':
    w = WordReplace(r'E:\PycharmProjects\office-tools\11.docx')
    w.replace_save('a.docx')
